﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MQRevo;

namespace MQCard
{
    public partial class frmMain : Form
    {
        public RevoCard card;
        public frmMain()
        {
            InitializeComponent();
            card= new RevoCard(1);
        }


        /// <summary>
        /// Detects if card is present 
        /// Whenever any other card operation is performed, the timer MUST BE DISABLED
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrPoll_Tick(object sender, EventArgs e)
        {
            // connect to card reader
            // polling ensures live information on card reader connection status
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            ConnectCardReaderResult ccrResult = CardComm.ConnectCardReader();
            switch (ccrResult)
            {
                case ConnectCardReaderResult.Success: //Reader connected
                    lblCardRdr.ForeColor = Color.DarkGreen;
                    lblCardRdr.Text = CardComm.cardReader;
                    tmrPoll.Enabled = true;
                    break;
                case ConnectCardReaderResult.NoReadersAvailable: //Reader not connected
                    lblCardRdr.ForeColor = Color.Red;
                    lblCardRdr.Text = "Not Detected";
                    tmrPoll.Enabled = true;
                    return;
                case ConnectCardReaderResult.Error: //Error connecting to reader
                    lblCardRdr.ForeColor = Color.Red;
                    lblCardRdr.Text = "Connection Error";
                    tmrPoll.Enabled = true;
                    return;
            }

            // Check if card is present on reader
            if (card.getCardID())
            {
                lblCardID.ForeColor = Color.DarkGreen;
                lblCardID.Text = card.cardID;

            }
            else
            {
                lblCardID.ForeColor = Color.Red;
                lblCardID.Text = "No Card Detected";
            }
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you wish to exit?","Exit",MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                System.Environment.Exit(0);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            tmrPoll.Enabled = true;
            CardComm.EstablishContext();
            cbGender.SelectedIndex = 0;
        }

        private void btnClearForm_Click(object sender, EventArgs e)
        {
            tbName.Text="";
            tbCardID.Text = "";

            dtpBirthDate.Value = new DateTime(1900, 1, 1);
            dtpExpiry.Value = new DateTime(1900, 1, 1);

            lblBalance.Text = "";
            lblPoints.Text = "";
            tbPoints.Text = "";
            tbAmt.Text = "";
            cbGender.SelectedIndex = 0;

            tbMemID.Text = "";
            tbEmail.Text = "";
            tbICPassport.Text = "";
            tbPhone.Text = "";

        }

        private void btnIssue_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            card.getCardID();
            RevoCard.ePurse purse = new RevoCard.ePurse();
            purse.merchantID = Convert.ToInt16(tbMerchant.Text);
            purse.programJoinDate= DateTime.Now;
            purse.purseExpiry= dtpExpiry.Value;
            purse.purseValue = 0;
            purse.memberID = tbMemID.Text;
            RevoCard.LoyaltyData ld = new RevoCard.LoyaltyData();
            ld.merchantID = Convert.ToInt16(tbMerchant.Text);
            ld.programJoinDate = DateTime.Now;
            ld.expiryDate = dtpExpiry.Value;
            ld.points = 0;
            ld.memberID = tbMemID.Text;

            if (card.issueCard(tbName.Text, dtpBirthDate.Value, Convert.ToChar(cbGender.SelectedItem),
               Convert.ToInt16(tbMerchant.Text), Convert.ToInt32(tbCardID.Text), Convert.ToInt16(tbTerminal.Text)
               , purse, ld, tbICPassport.Text, tbPhone.Text, tbEmail.Text,1))
                MessageBox.Show("Card Issued Successfully!");
            else
                MessageBox.Show("Error Issuing Card: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnReadCard_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            card.getCardID();
            if (card.readPurseCard(Convert.ToInt16(tbMerchant.Text)))
            {
                tbName.Text = card.cardHolderName;
                dtpBirthDate.Value = card.cardHolderDOB;
                dtpExpiry.Value = card.purse.purseExpiry;
                tbMemID.Text = card.purse.memberID;
                if (card.cardHolderGender == 'M')
                    cbGender.SelectedIndex = 0;
                else cbGender.SelectedIndex = 1;
                tbCardID.Text = card.issueCardID.ToString();
                Single purseDollarAmt = Convert.ToSingle(card.purse.purseValue)/100;
                lblBalance.Text = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", purseDollarAmt);

                if (card.readLoyaltyCard(Convert.ToInt16(tbMerchant.Text))){
                    string points = "";
                    foreach (RevoCard.LoyaltyData data in card.loyalty)
                    {
                        points = points + "Loyalty Points " + data.order.ToString() + ": " + data.points.ToString() + " points\n";
                    }
                    lblPoints.Text = points;
                }
                else MessageBox.Show("Error Reading Points: " + card.lastErr);
            }
            else MessageBox.Show("Error Reading Card: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnTopUp_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            card.getCardID();
            decimal amt = Decimal.Round(Convert.ToDecimal(tbAmt.Text),2);//round to 2 decimal places
            amt = amt * 100; //convert to cents
            if (card.topupDeductPurse(Convert.ToInt16(tbMerchant.Text), Convert.ToInt32(amt), true))
            {
                //read back the purse value
                if (card.readPurseCard(Convert.ToInt16(tbMerchant.Text)))
                {
                    Single purseDollarAmt = Convert.ToSingle(card.purse.purseValue) / 100;
                    lblBalance.Text = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", purseDollarAmt);
                }
            
                MessageBox.Show("Top Up Successful!");
            }
            else MessageBox.Show("Error Adding Value: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnDeduct_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false; 
            CardComm.EstablishContext();
            card.getCardID();
            
            decimal amt = Decimal.Round(Convert.ToDecimal(tbAmt.Text), 2);//round to 2 decimal places
            amt = amt * 100; //convert to cents

            if (card.topupDeductPurse(Convert.ToInt16(tbMerchant.Text), Convert.ToInt32(amt), false))
            {
                //read back the purse amount
                if (card.readPurseCard(Convert.ToInt16(tbMerchant.Text)))
                {
                    Single purseDollarAmt = Convert.ToSingle(card.purse.purseValue) / 100;
                    lblBalance.Text = String.Format("{0:$#,##0.00;($#,##0.00);Zero}", purseDollarAmt);
                }
                MessageBox.Show("Deduction Successful!");
            }
            else MessageBox.Show("Error Deducting Value: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            card.getCardID();
            if (card.updateCard(tbName.Text, dtpBirthDate.Value, Convert.ToChar(cbGender.SelectedItem),
                Convert.ToInt32(tbCardID.Text), Convert.ToInt16(tbMerchant.Text), dtpExpiry.Value, tbICPassport.Text, tbPhone.Text, tbEmail.Text, tbMemID.Text))
                MessageBox.Show("Card Updated Successfully!");
            else
                MessageBox.Show("Error Updating Card: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnLTopup_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false;
            CardComm.EstablishContext();
            card.getCardID();
            if (card.topupDeductPoints(Convert.ToInt16(tbMerchant.Text),Convert.ToInt16(cboLoyaltyNo.SelectedItem), Convert.ToInt32(tbPoints.Text), true))
            {
                if (card.readLoyaltyCard(Convert.ToInt16(tbMerchant.Text)))
                {
                    string points = "";
                    foreach (RevoCard.LoyaltyData data in card.loyalty)
                    {
                        points = points + "Loyalty Points " + data.order.ToString() + ": " + data.points.ToString() + " points\n";
                    }
                    lblPoints.Text = points;
                }

                MessageBox.Show("Top Up Successful!");
            }
            else MessageBox.Show("Error Adding Points: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

        private void btnLDeduct_Click(object sender, EventArgs e)
        {
            tmrPoll.Enabled = false; 
            CardComm.EstablishContext();
            card.getCardID();
            int order = cboLoyaltyNo.SelectedIndex;
            order += 1;
            if (card.topupDeductPoints(Convert.ToInt16(tbMerchant.Text),Convert.ToInt16(order), Convert.ToInt32(tbPoints.Text), false))
            {
                if (card.readLoyaltyCard(Convert.ToInt16(tbMerchant.Text)))
                {
                    string points = "";
                    foreach (RevoCard.LoyaltyData data in card.loyalty)
                    {
                        points = "Loyalty Points " + data.order.ToString() + ": " + data.points.ToString() + "points\n";
                    }
                    lblPoints.Text = points;
                }

                MessageBox.Show("Deduction Successful!");
            }
            else MessageBox.Show("Error Deducting Points: " + card.lastErr);
            CardComm.ReleaseContext();
            tmrPoll.Enabled = true;
        }

             
    }
}
